<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" src="/favicon.ico" alt="logo">
            <div class="title"> 云图库</div>
          </div>
        </RouterLink>
      </a-col>
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
      <a-col flex="128px">
        <div v-if="loginUserStore.loginUser.id">
          <a-dropdown>
            <ASpace>
              <a-avatar :src="loginUserStore.loginUser.userAvatar ?? 'src/assets/user_head.png'"/>
              {{ loginUserStore.loginUser.userName ?? '无名' }}
            </ASpace>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="toInfo">
                  <EditOutlined />
                  个人中心
                </a-menu-item>
                <a-menu-item @click="doLogout">
                  <LogoutOutlined/>
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" href="/user/login">登录/注册</a-button>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { LogoutOutlined,EditOutlined } from '@ant-design/icons-vue';
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router';
import { useLoginUserStore } from '@/stores/user.ts'
import { routes } from '@/router/routes.ts'
import { checkAccess } from '@/router/role.ts'
import { userLogoutUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'

const current = ref<string[]>([]);
const items = computed(() =>
  routes
  .filter((e) => {
    if (e.meta?.show == false) {
      return false;
    }
    return checkAccess(loginUserStore.loginUser, e?.meta?.authCheck as string);

  })
  .map((e) => {
    return {
      key: e.path,
      label: e.name,
      title: e.name,
      icon: e.meta?.icon,
    }
  }),
)
const router = useRouter();
const loginUserStore = useLoginUserStore();
const doMenuClick = ({ key }: { key: string}) => {
  router.push({
    path: key,
  });
}
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  console.log(res)
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败' + res.data.message)
  }
}
const toInfo = () => {
  router.push('/user/info')
}
router.afterEach((to) => {
  current.value = [to.path];
})
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
